<template>
	<view class="page-container">
		<view class="form-container">
			<view class="form-item">
				<view class="form-label">名称</view>
				<view class="form-control">
					<uni-easyinput v-model="cezhanitem.name" placeholder="请输入测站名称"></uni-easyinput>
				</view>
			</view>


			<!-- 左坡角部分 -->
			<view class="form-item">
				<view class="form-label">左坡角</view>
				<view class="form-control with-unit">
					<uni-easyinput v-model="cezhanitem.lSA" type="digit" placeholder="请输入"
						@input="updateSlopeRatioFromAngle('l')"></uni-easyinput>
					<view class="unit">°</view>
				</view>
			</view>

			<view class="slope-ratio-container">
				<view class="slope-ratio-label">左坡比</view>
				<view class="slope-ratio-inputs">
					<view class="slope-ratio-input">
						<input class="input-field" v-model="slopeRatio.l.left" placeholder="垂直" type="digit"
							@input="calculateSlopeAngle('l')">
						<view class="underline"></view>
					</view>
					<view class="ratio-separator">:</view>
					<view class="slope-ratio-input">
						<input class="input-field" v-model="slopeRatio.l.right" placeholder="水平" type="digit"
							@input="calculateSlopeAngle('l')">
						<view class="underline"></view>
					</view>
				</view>
			</view>

			<!-- 右坡角部分 -->
			<view class="form-item">
				<view class="form-label">右坡角</view>
				<view class="form-control with-unit">
					<uni-easyinput v-model="cezhanitem.rSA" type="digit" placeholder="请输入"
						@input="updateSlopeRatioFromAngle('r')"></uni-easyinput>
					<view class="unit">°</view>
				</view>
			</view>

			<view class="slope-ratio-container">
				<view class="slope-ratio-label">右坡比</view>
				<view class="slope-ratio-inputs">
					<view class="slope-ratio-input">
						<input class="input-field" v-model="slopeRatio.r.left" placeholder="垂直" type="digit"
							@input="calculateSlopeAngle('r')">
						<view class="underline"></view>
					</view>
					<view class="ratio-separator">:</view>
					<view class="slope-ratio-input">
						<input class="input-field" v-model="slopeRatio.r.right" placeholder="水平" type="digit"
							@input="calculateSlopeAngle('r')">
						<view class="underline"></view>
					</view>
				</view>
			</view>

			<view class="form-item">
				<view class="form-label">测量方法</view>
				<view class="form-control">
					<uni-data-checkbox v-model="cezhanitem.morencefa" :localdata="range3"></uni-data-checkbox>
				</view>
			</view>
			<view class="form-item">
				<view class="form-label">多普勒</view>
				<view class="form-control">
					<uni-data-checkbox v-model="cezhanitem.doppler" :localdata="range4"></uni-data-checkbox>
				</view>
			</view>

			<view class="form-item">
				<view class="form-label">左岸系数</view>
				<view class="form-control">
					<uni-easyinput v-model="cezhanitem.kL" type="digit" placeholder="请输入"></uni-easyinput>
				</view>
			</view>

			<view class="form-item">
				<view class="form-label">右岸系数</view>
				<view class="form-control">
					<uni-easyinput v-model="cezhanitem.kR" type="digit" placeholder="请输入"></uni-easyinput>
				</view>
			</view>
			<view class="form-item">
				<view class="form-label">渠底宽度</view>
				<view class="form-control with-unit">
					<uni-easyinput v-model="cezhanitem.qudikuandu" type="digit" placeholder="请输入"></uni-easyinput>
					<view class="unit">m</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-label">测线条数</view>
				<view class="form-control">
					<uni-data-select :clear="false" v-model="cezhanitem.measurementModeList[1].value.length"
						:localdata="range1" placeholder="请选择" @change="change1"></uni-data-select>
				</view>
			</view>

			<view class="measurement-lines" v-if="cezhanitem.measurementModeList[1].value.length > 0">
				<view class="line-header">
					<view class="line-cell">测线编号</view>
					<view class="line-cell">水平坐标(m)</view>
				</view>
				<view class="line-row" v-for="(item, index) in cezhanitem.measurementModeList[1].value" :key="index">
					<view class="line-cell">{{ item.id }}</view>
					<view class="line-cell with-unit">
						<u--input v-model="item.cR" placeholder="请输入" border="none" type="digit"></u--input>
						<view class="unit">m</view>
					</view>
				</view>
			</view>

			<view class="form-actions">
				<u-button @click="handleSave" type="primary" shape="circle" text="保存到本地" :disabled="isSaving"
					:loading="isSaving"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				slopeRatio: {
					l: {
						left: '1',
						right: '2'
					}, // 左坡比 (垂直:水平)
					r: {
						left: '1',
						right: '2'
					} // 右坡比 (垂直:水平)
				},
				// 保存按钮状态控制
				isSaving: false, // 是否正在保存中（用于禁用按钮和显示loading状态）
				lastClickTime: 0, // 上次点击保存按钮的时间戳（用于防抖）

				// 测站表单数据
				cezhanitem: {
					name: '测站名称可修改', // 测站名称
					qudikuandu: '', // 渠底宽度（单位：m）
					lSA: '26.5651', // 左坡角（单位：°）
					rSA: '26.5651', // 右坡角（单位：°）
					morencefa: 1, // 测量方法（1-一点法，3-三点法）
					doppler: 1, // 多普勒品牌
					kL: '0.95', // 左岸系数
					kR: '0.95', // 右岸系数
					cexiantiaoshu: 0, // 当前选择的测线条数
					measurementModeList: [ // 测线数据集合
						{
							value: '0'
						}, // 保留字段
						{
							value: []
						}, // 测线数据数组
						{
							value: []
						} // 保留字段
					]
				},
				// 测线条数选项（1-9条）
				range1: Array.from({
					length: 9
				}, (_, i) => ({
					text: `${i + 1}条测线`,
					value: i + 1
				})),

				// 测量方法选项
				range3: [{
						text: '一点法',
						value: 1
					},
					{
						text: '三点法',
						value: 3
					}
				],
				// 多普勒品牌
				range4: [{
						text: '德希',
						value: 1
					},
					{
						text: '大禹',
						value: 2
					},
					{
						text: '睿鑫',
						value: 3
					}
				]
			}
		},
		methods: {
			calculateSlopeAngle(side) {
				const ratio = this.slopeRatio[side];
				if (ratio.left && ratio.right) {
					// 计算角度: arctan(垂直/水平) * (180/π)
					const angle = Math.atan(ratio.left / ratio.right) * (180 / Math.PI);
					this.cezhanitem[`${side}SA`] = angle.toFixed(4);
				}
			},

			// 根据坡角反算坡比
			updateSlopeRatioFromAngle(side) {
				if (this.cezhanitem[`${side}SA`]) {
					const angle = parseFloat(this.cezhanitem[`${side}SA`]);
					// 计算坡比 (假设水平为1，计算垂直值)
					const vertical = Math.tan(angle * Math.PI / 180).toFixed(4);
					this.slopeRatio[side].left = vertical;
					this.slopeRatio[side].right = '1';
				}
			},
			change1(e) {
				this.cezhanitem.cexiantiaoshu = e
				this.cezhanitem.measurementModeList[1].value = Array.from({
						length: e
					},
					(_, i) => ({
						id: i + 1,
						cR: ''
					})
				)
			},
			handleSave() {
				// 防重复点击：1秒内只能点击一次
				const now = Date.now()
				if (now - this.lastClickTime < 1000) {
					uni.showToast({
						title: '操作过于频繁，请稍后再试',
						icon: 'none'
					})
					return
				}
				this.lastClickTime = now
				this.isSaving = true

				this.saveCezhan().finally(() => {
					this.isSaving = false
				})
			},
			async saveCezhan() {
				try {
					if (!this.validateForm()) return

					this.cezhanitem.id = Date.now()
					const datalist = this.vuex_saveCezhandata || []
					uni.$u.vuex('vuex_saveCezhandata', [this.cezhanitem, ...datalist])

					await new Promise(resolve => {
						uni.showToast({
							title: '保存成功',
							icon: 'success',
							duration: 1500,
							complete: resolve
						})
					})

					uni.navigateBack()
				} catch (error) {
					console.error('保存失败:', error)
					uni.showToast({
						title: '保存失败，请重试',
						icon: 'none'
					})
					throw error // 继续抛出错误以便外层处理
				}
			},
			validateForm() {
				const requiredFields = [{
						field: 'name',
						message: '请输入测站名称'
					},
					{
						field: 'qudikuandu',
						message: '请输入渠底宽度'
					},
					{
						field: 'cexiantiaoshu',
						message: '请选择测线条数',
						validator: v => v > 0
					}
				]

				for (const {
						field,
						message,
						validator
					}
					of requiredFields) {
					const value = this.cezhanitem[field]
					if (validator ? !validator(value) : !value) {
						uni.showToast({
							title: message,
							icon: 'none'
						})
						return false
					}
				}

				// 验证测线坐标是否全部填写
				if (this.cezhanitem.measurementModeList[1].value.some(item => !item.cR)) {
					uni.showToast({
						title: '请填写所有测线坐标',
						icon: 'none'
					})
					return false
				}

				return true
			}
		}
	}
</script>

<style scoped lang="scss">
	// 坡比
	.slope-ratio-container {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;

		.slope-ratio-label {
			width: 180rpx;
			font-size: 30rpx;
			color: #606266;
		}

		.slope-ratio-inputs {
			flex: 1;
			display: flex;
			align-items: center;
		}
	}

	.slope-ratio-input {
		flex: 1;
		position: relative;

		.input-field {
			width: 100%;
			height: 70rpx;
			padding: 0 20rpx;
			font-size: 28rpx;
			text-align: center;
			border: none;
			outline: none;
		}

		.underline {
			height: 2rpx;
			background-color: #dcdfe6;
			margin-top: 4rpx;
		}
	}

	.ratio-separator {
		padding: 0 20rpx;
		font-size: 28rpx;
		color: #606266;
	}

	.page-container {
		padding: 20rpx;
		background-color: #f5f7fa;
	}

	.form-container {
		background: #ffffff;
		border-radius: 16rpx;
		padding: 20rpx;
	}

	.form-item {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.form-item .form-label {
		width: 180rpx;
		font-size: 30rpx;
		color: #606266;
	}

	.form-item .form-control {
		flex: 1;
		position: relative;
	}

	.form-control.with-unit .uni-easyinput,
	.form-control.with-unit .uni-input-wrapper {
		padding-right: 60rpx !important;
	}

	.form-control .unit {
		position: absolute;
		right: 20rpx;
		top: 50%;
		transform: translateY(-50%);
		color: #999;
		font-size: 28rpx;
		z-index: 2;
	}

	.measurement-lines {
		margin: 30rpx 0;
		border: 1rpx solid #ebeef5;
		border-radius: 8rpx;
		overflow: hidden;
	}

	.measurement-lines .line-header,
	.measurement-lines .line-row {
		display: flex;
		align-items: center;
	}

	.measurement-lines .line-header {
		background-color: #409eff;
		color: #ffffff;
	}

	.measurement-lines .line-row {
		background: #ffffff;
		border-bottom: 1rpx solid #ebeef5;
	}

	.measurement-lines .line-row:last-child {
		border-bottom: none;
	}

	.measurement-lines .line-cell {
		flex: 1;
		padding: 20rpx;
		text-align: center;
		font-size: 26rpx;
		position: relative;
	}

	.measurement-lines .line-cell.with-unit .u-input {
		padding-right: 60rpx !important;
	}

	.measurement-lines .line-cell .unit {
		position: absolute;
		right: 30rpx;
		top: 50%;
		transform: translateY(-50%);
		color: #999;
		font-size: 26rpx;
	}

	.form-actions {
		margin: 40rpx 60rpx 0;
	}
</style>
<style>
	page {
		background-color: #f5f7fa;
	}
</style>